//需要更多精品unity cocos laya 代码联系 BatchMichaelbXKxyJ@gmail.com
//电报群免费送9个cocos https://t.me/cocoscreatorcode


module.exports = {
    isSupportFunction: function (t, e) {
        return !!t || (console.log("不能使用" + e), !1);
    },
    init: function (t) {
        this.gameName = t.gameName, this.gameAppid = t.gameAppid, this.secret = t.secret,
            console.log(this.gameName);
    },
    hitBox: function (t) {
        wx.showToast({
            title: t,
            icon: "none",
            duration: 2500
        });
    },
    onShow: function (t) {
        var e = this;
        wx.onShow(function (n) {
            console.log("on show"), console.log(e.type), e.type && t && (t({
                type: e.type
            }), e.type = null);
        });
    },
    getGroupOpenid: function (t) {
        wx.request({
            url: "https://www.7cgames.cn:8070/getDecryptedData",
            data: {
                openId: t.playerOpenid,
                encryptedData: t.encryptedData,
                iv: t.iv
            },
            header: {
                "Content-Type": "application/json"
            },
            method: "POST",
            success: t.success
        });
    },
    login: function (t) {
        var e = this;
        console.log("Wechat login");
        wx.login({
            success: function (n) {
                e.getPlayerOpenid({
                    gameName: e.gameName,
                    gameAppid: e.gameAppid,
                    secret: e.secret,
                    code: n.code,
                    success: function (n) {
                        e.playerOpenid = n.data.openid, t && t(n.data.openid), console.log("get player openid success, " + e.playerOpenid);
                    },
                    fail: function () {
                        console.log("get player openid fail");
                    }
                });
            }
        });
    },
    getPlayerOpenid: function (t) {
        console.log("test data code : " + t.code), wx.request({
            url: "https://www.7cgames.cn:8070/getOpenId",
            data: {
                gameName: t.gameName,
                appid: t.gameAppid,
                secret: t.secret,
                js_code: t.code,
                grant_type: "authorization_code"
            },
            header: {
                "Content-Type": "application/json"
            },
            method: "POST",
            success: t.success,
            fail: t.fail
        });
    },
    openShare: function (t, e) {
        if (this.isSupportFunction(wx.showShareMenu, "打开分享")) {
            wx.showShareMenu({
                withShareTicket: !0
            });
            var n = t.length,
                o = 0;
            wx.onShareAppMessage(function () {
                var i = o++ % n;
                return {
                    title: t[i],
                    imageUrl: e[i]
                };
            });
        }
    },
    share: function (t) {
        if (this.isSupportFunction(wx.shareAppMessage, "分享")) {
            console.log("微信主动分享"), wx.shareAppMessage({
                title: t.title,
                imageUrl: t.imageUrl,
                query: "openid=" + this.playerOpenid + "&utc=" + t.utc + "&type=" + t.type
            }), this.type = t.type;
        }
    },
    preloadBannerAD: function (t) {
        var e = this;
        this.isSupportFunction(wx.createBannerAd, "预加载条形广告") && (this.bannerAD = wx.createBannerAd({
            adUnitId: t,
            style: {
                left: 0,
                top: wx.getSystemInfoSync().windowHeight - 43 * wx.getSystemInfoSync().windowWidth / 150,
                width: 300
            }
        }), this.bannerAD.onResize(function (t) {
            e.setBannerADSameMaxHeight(), e.bannerAD.style.left = (wx.getSystemInfoSync().windowWidth - e.bannerAD.style.realWidth) / 2,
                e.bannerAD.style.top = wx.getSystemInfoSync().windowHeight - e.bannerAD.style.realHeight,
                console.log("wx.h:" + e.bannerAD.style.realHeight), console.log("wx.w:" + e.bannerAD.style.realWidth);
        }), this.bannerAD.onError(function (t) {
            console.log("banner 加载失败" + t);
        }));
    },
    updateBannerAD: function (t) {
        null != this.bannerAD ? (this.bannerAD.destroy(), this.bannerAD = null, this.preloadBannerAD(t)) : console.log("请先preloadBannerAD");
    },
    setBannerADminWidth: function () {
        null != this.bannerAD ? this.bannerAD.style.width = 300 : console.log("请先preloadBannerAD");
    },
    setBannerADSameMaxHeight: function () {
        null != this.bannerAD ? this.bannerAD.style.realHeight / this.bannerAD.style.realWidth > .346 ? this.bannerAD.style.width = 43 * wx.getSystemInfoSync().windowWidth / 52 : this.bannerAD.style.width = wx.getSystemInfoSync().windowWidth : console.log("请先preloadBannerAD");
    },
    setBannerADNormalWidth: function () {
        null != this.bannerAD ? wx.getSystemInfoSync().windowHeight / wx.getSystemInfoSync().windowWidth < 1.4 ? this.bannerAD.style.width = 300 : this.bannerAD.style.width = wx.getSystemInfoSync().windowWidth : console.log("请先preloadBannerAD");
    },
    showBannerAD: function () {
        null != this.bannerAD ? this.bannerAD.show() : console.log("请先preloadBannerAD");
    },
    hideBannerAD: function () {
        null != this.bannerAD ? this.bannerAD.hide() : console.log("请先preloadBannerAD");
    },
    preloadRewardedAD: function (t) {
        var e = this;
        this.isSupportFunction(wx.createRewardedVideoAd, "预加载视频广告") && (this.video = !1,
            this.rewardedAD = wx.createRewardedVideoAd({
                adUnitId: t
            }), this.rewardedAD.onLoad(function () {
                console.log("加载成功"), e.video = !0;
            }), this.rewardedAD.onError(function (t) {
                console.log("加载失败" + t), e.video = !1;
            }));
    },
    isOkVideo: function () {
        return this.video;
    },
    showRewardedAD: function (t) {
        if (null != this.rewardedAD) {
            var e = this;
            this.rewardedAD.show().then(function () {
                e.callback = t, e.video = !1, console.log("激励视频 广告显示");
            });
        } else console.log("请先preloadRewardedAD"), wx.showModal({
            title: "提示",
            content: "当前微信版本过低，无法正常使用，请升级到最新微信版本后重试。"
        });
    },
    closeRewardedAD: function () {
        var t = this;
        null != this.rewardedAD ? this.rewardedAD.onClose(function (e) {
            return e && e.isEnded || void 0 === e ? (console.log("正常结束"), t.callback ? (t.callback(),
                t.callback = null) : console.log("请先设置callBack"), !0) : (console.log("中途退出"), !1);
        }) : console.log("请先preloadRewardedAD");
    },
    openData: cc.Enum({
        closeRank: 0,
        openRank: 1,
        submitScore: 3,
        gameOverRank: 4,
        groupFriendRank: 5
    }),
    isSupportOpenData: function () {
        var t = this.isSupportFunction(wx.getOpenDataContext, "开放域");
        return t || wx.showModal({
            title: "提示",
            content: "当前微信版本过低，无法正常使用，请升级到最新微信版本后重试。"
        }), t;
    },

    initUserAuthorization: function() {
        console.log("自动授权");
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    console.log("已经授权，可以直接调用 getUserInfo 获取头像昵称");
 
                    wx.getUserInfo({
                        success(res) {
                            console.log("获取权限成功：", res);
                        },
                        fail(err) {
                            console.log("获取权限失败：", err);
                        }
                    })
                } else {
                    wx.requirePrivacyAuthorize({
                        success: res => {
                            console.log("原因：：", res);
 
                            var info = wx.getSystemInfoSync()
                            // 全屏透明按钮
                            let button = wx.createUserInfoButton({
                                type: 'text',
                                text: '',
                                style: {
                                    width: info.screenWidth,
                                    height: info.screenHeight,
                                    left: 0,
                                    top: 0,
                                    backgroundColor: '#00000000',//最后两位为透明度
                                    color: '#ffffff',
                                    fontSize: 20,
                                    textAlign: "center"
                                }
                            })
                            button.onTap((res) => {
                                console.log("结果::", res);
                                if (res.userInfo) {
                                    console.log("授权成功");
                                }
                                button.hide();
                            })
                        },
                        fail: (res) => {
                            console.log("拒绝", res);
                        },
                        complete: (res) => {
                            console.log("结果", res);
                        }
                    })
                }
            }
        });
    },
    closeRank: function () {
        wx.getOpenDataContext().postMessage({
            //messageType: this.openData.closeRank,
            message: "clear",
            //MAIN_MENU_NUM: "x1"
        });
    },
    openRank: function () {
        let score = Math.round(Math.random()*10);
        wx.getOpenDataContext().postMessage({
            //messageType: this.openData.openRank,
            message: score,
            //MAIN_MENU_NUM: "x1"
        });
        console.log("send open rank");
    },
    gameOverRank: function () {
        wx.postMessage({
            messageType: this.openData.gameOverRank,
            MAIN_MENU_NUM: "x1"
        });
    },
    saveScore : function(k,v){
        wx.setUserCloudStorage({
            KVDataList : [{ key : k , value : v}], 
            //这里接口接收的数据value好像只支持string类型，不成功可以将数据toString试试
            success : res =>{
                console.log("save score success");
            },
            fail : res =>{
                console.log("save score fail");
            }
        });        
    },
    submitScore: function (t) {
        wx.postMessage({
            messageType: this.openData.submitScore,
            MAIN_MENU_NUM: "x1",
            score: t
        });
    },
    groupFriendRank: function (t, e) {
        var n = this;
        wx.shareAppMessage({
            title: t,
            imageUrl: e,
            success: function (t) {
                void 0 != t.shareTickets && t.shareTickets.length > 0 && wx.postMessage({
                    messageType: n.openData.groupFriendRank,
                    MAIN_MENU_NUM: "x1",
                    shareTicket: t.shareTickets[0]
                });
            }
        });
    },
    initMoreGame: function () {
        var t = this;
        this.moreGame = {
            key: 0,
            length: 0,
            list: null
        }, wx.request({
            url: "https://www.7cgames.cn/GameRes/7CGamesBoxWX/QRCode/WXGameCode.json",
            headers: {
                "Content-Type": "application/json"
            },
            success: function (e) {
                t.moreGame.list = e.data.data, t.moreGame.length = t.moreGame.list.length, console.log("moreGameList", t.moreGame.list);
            }
        });
    },
    showMoreGameQR: function () {
        if (this.moreGame.list) {
            var t = this.moreGame.key++ % this.moreGame.length,
                e = this.moreGame.list[t];
            e.appid == this.gameAppid ? this.toMiniProgram() : wx.previewImage({
                urls: [e.QRCode],
                success: function () {
                    console.log("wechat previewImage success...");
                }
            });
        } else console.log("moreGameList 为空，未获取更多游戏列表");
    },
    getPlatform: function (t) {
        wx.getSystemInfo({
            success: function (e) {
                t(e.platform);
            }
        });
    },
    toMiniProgram: function (t) {
        wx.navigateToMiniProgram && t ? wx.navigateToMiniProgram({
            appId: t,
            path: "",
            success: function (t) {
                console.log("打开成功");
            }
        }) : this.showMoreGameQR();
    },
    openMiniGame: function (t) {
        this.toMiniProgram(t);
    },
    openMiniProgram: function (t) {
        this.getPlatform(function (e) {
            "ios" == e ? (console.log("ios"), this.toMiniProgram()) : "android" == e ? (console.log("android"),
                this.toMiniProgram(t)) : "devtools" == e && (console.log("devtools"), this.toMiniProgram());
        }.bind(this));
    }
}